package socket

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"fmt"
)

//编码
func EncoderData(response *Response) []byte {
	//头
	headb, _ := hex.DecodeString("5A55")
	//组装流水号
	serialnumb, _ := IntToBytes(int(response.SerialNum), 2)
	//协议版本
	versionb, _ := IntToBytes(1, 1)
	//命令
	cmdb, _ := IntToBytes(response.Cmd, 1)
	//16进制数据
	data, _ := hex.DecodeString(hex.EncodeToString(response.Data))
	//帧长度
	length := 4 + 2 + 1 + 1 + 1 + len(data)
	lengthb, _ := IntToBytes(length, 4)
	//校验和
	checksumb, _ := IntToBytes(length+2, 1)
	return BytesCombine(headb, lengthb, serialnumb, versionb, cmdb, data, checksumb)
}

func BytesCombine(pBytes ...[]byte) []byte {
	return bytes.Join(pBytes, []byte(""))
}

//整形转换成字节
func IntToBytes(n int, b byte) ([]byte, error) {
	switch b {
	case 1:
		tmp := int8(n)
		bytesBuffer := bytes.NewBuffer([]byte{})
		binary.Write(bytesBuffer, binary.BigEndian, &tmp)
		return bytesBuffer.Bytes(), nil
	case 2:
		tmp := int16(n)
		bytesBuffer := bytes.NewBuffer([]byte{})
		binary.Write(bytesBuffer, binary.BigEndian, &tmp)
		return bytesBuffer.Bytes(), nil
	case 3, 4:
		tmp := int32(n)
		bytesBuffer := bytes.NewBuffer([]byte{})
		binary.Write(bytesBuffer, binary.BigEndian, &tmp)
		return bytesBuffer.Bytes(), nil
	}
	return nil, fmt.Errorf("IntToBytes b param is invaild")
}
